<template>
  <div class="page-container">
    <el-card v-loading="loading" class="main-card">
      <template #header>
        <div class="card-header">
          <div>
            <h3>{{ customNodeType?.name || '自定义节点类型' }} - 版本管理</h3>
            <el-tag v-if="customNodeType?.currentVersion" size="small" type="success">
              当前版本: v{{ customNodeType.currentVersion }}
            </el-tag>
            <el-tag v-else size="small" type="info">未发布</el-tag>
          </div>
          <div class="header-actions">
            <el-button @click="goBack">返回详情</el-button>
            <el-button type="primary" @click="goToNodeTypesList">返回列表</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="versions"
        style="width: 100%"
        border
      >
        <el-table-column prop="version" label="版本号" width="120">
          <template #default="{ row }">
            <span class="version-tag">v{{ row.version }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="版本说明" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="isCurrentVersion(row) ? 'success' : 'info'">
              {{ isCurrentVersion(row) ? '当前版本' : '历史版本' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="引用事件" width="100">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="info" 
              @click="viewReferencingEvents(row)"
              plain
            >
              查看事件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="引用计数" width="100">
          <template #default="{ row }">
            <span class="reference-count">
              {{ versionReferenceCount[row.id] || 0 }}
              <el-tooltip content="引用此版本的事件数量" placement="top">
                <el-icon class="info-icon"><el-icon-info /></el-icon>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button 
                size="small" 
                type="primary" 
                @click="viewVersionDetail(row)"
              >
                查看代码
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="createFromVersion(row)"
              >
                基于此版本
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="confirmPublish(row)"
                :disabled="isCurrentVersion(row)"
                :loading="publishing && publishingVersionId === row.id"
              >
                {{ isCurrentVersion(row) ? '已发布' : '发布此版本' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="versions.length === 0" class="empty-data">
        <el-empty description="暂无版本记录">
          <el-button type="primary" @click="goBack">
            返回创建版本
          </el-button>
        </el-empty>
      </div>
    </el-card>
    
    <!-- 版本详情查看弹窗 -->
    <el-dialog
      v-model="versionDetailVisible"
      :title="`版本 v${currentVersionDetail?.version || ''} 详情`"
      width="700px"
    >
      <div v-if="currentVersionDetail" class="version-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="版本号">v{{ currentVersionDetail.version }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentVersionDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="版本说明" :span="2">
            {{ currentVersionDetail.description }}
            <el-tag v-if="currentVersionDetail.description && currentVersionDetail.description.includes('基于 v')" 
              size="small" type="warning" style="margin-left: 10px">
              基于历史版本
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="code-section">
          <h4>参数说明</h4>
          <div class="code-box params-docs">
            {{ currentVersionDetail.parametersDocs || '无参数说明' }}
          </div>
          
          <h4>返回值说明</h4>
          <div class="code-box return-docs">
            {{ currentVersionDetail.returnDocs || '无返回值说明' }}
          </div>
          
          <h4>节点代码</h4>
          <div class="code-box">
            <pre>{{ currentVersionDetail.code }}</pre>
          </div>
        </div>
        
        <template v-if="isCurrentVersion(currentVersionDetail)">
          <el-alert
            type="success"
            :closable="false"
            title="此版本为当前使用版本"
            description="此版本已发布并作为当前使用版本"
            show-icon
          />
        </template>
        <template v-else>
          <el-alert
            type="info"
            :closable="false"
            title="此版本为历史版本"
            description="您可以发布此版本，将其设为当前使用版本"
            show-icon
          />
          <div class="dialog-actions">
            <el-button 
              type="success" 
              @click="confirmPublish(currentVersionDetail)"
              :loading="publishing && publishingVersionId === currentVersionDetail.id"
            >
              发布此版本
            </el-button>
          </div>
        </template>
      </div>
    </el-dialog>
    
    <!-- 引用事件列表弹窗 -->
    <el-dialog
      v-model="referencingEventsVisible"
      :title="`引用版本 v${currentEventVersion?.version || ''} 的事件列表`"
      width="600px"
    >
      <div v-loading="loadingEvents">
        <div v-if="referencingEvents.length > 0">
          <el-table :data="referencingEvents" style="width: 100%">
            <el-table-column prop="name" label="事件名称" />
            <el-table-column prop="category" label="所属分类" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  @click="goToEvent(row.id)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-if="totalEvents > referencingEvents.length"
            layout="prev, pager, next"
            :total="totalEvents"
            :page-size="eventsPageSize"
            :current-page="eventsCurrentPage"
            @current-change="handleEventsPageChange"
            class="pagination"
          />
        </div>
        <el-empty v-else description="暂无引用此版本的事件" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled as ElIconInfo } from '@element-plus/icons-vue'

const store = useStore()
const router = useRouter()
const route = useRoute()

const loading = ref(false)
const publishing = ref(false)
const publishingVersionId = ref(null)
const versionDetailVisible = ref(false)
const currentVersionDetail = ref(null)

// 事件引用相关
const referencingEventsVisible = ref(false)
const loadingEvents = ref(false)
const referencingEvents = ref([])
const currentEventVersion = ref(null)
const totalEvents = ref(0)
const eventsCurrentPage = ref(1)
const eventsPageSize = ref(10)

// 在script setup中添加
const versionReferenceCount = ref({}) // 存储每个版本的引用计数

// 获取自定义节点类型详情和版本列表
const fetchData = async () => {
  loading.value = true
  try {
    await store.dispatch('fetchCustomNodeTypeById', route.params.id)
    await store.dispatch('fetchCustomNodeVersions', route.params.id)
    
    // 获取每个版本的引用计数
    fetchVersionReferenceCounts()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 添加新函数，获取所有版本的引用计数
const fetchVersionReferenceCounts = async () => {
  try {
    const counts = {}
    const promises = store.state.customNodeVersions.map(async (version) => {
      try {
        const data = await store.dispatch('fetchVersionEvents', {
          versionId: version.id,
          page: 1,
          pageSize: 1
        })
        counts[version.id] = data.total
      } catch (error) {
        console.error(`获取版本 ${version.id} 引用计数失败:`, error)
        counts[version.id] = 0
      }
    })
    
    await Promise.all(promises)
    versionReferenceCount.value = counts
  } catch (error) {
    console.error('获取版本引用计数失败:', error)
  }
}

// 查看引用特定版本的事件列表
const viewReferencingEvents = async (version) => {
  currentEventVersion.value = version
  referencingEventsVisible.value = true
  eventsCurrentPage.value = 1
  await fetchReferencingEvents(version.id, 1)
}

// 获取引用特定版本的事件
const fetchReferencingEvents = async (versionId, page) => {
  loadingEvents.value = true
  referencingEvents.value = []
  
  try {
    const data = await store.dispatch('fetchVersionEvents', {
      versionId,
      page,
      pageSize: eventsPageSize.value
    })
    
    referencingEvents.value = data.events
    totalEvents.value = data.total
  } catch (error) {
    console.error('获取引用事件列表失败:', error)
    ElMessage.error('获取引用事件列表失败')
  } finally {
    loadingEvents.value = false
  }
}

// 处理事件分页变化
const handleEventsPageChange = (page) => {
  eventsCurrentPage.value = page
  fetchReferencingEvents(currentEventVersion.value.id, page)
}

// 跳转到事件详情页
const goToEvent = (eventId) => {
  router.push(`/events/${eventId}`)
}

const customNodeType = computed(() => store.state.currentCustomNodeType)
const versions = computed(() => {
  // 按创建时间倒序排列，最新创建的在前
  return [...store.state.customNodeVersions].sort((a, b) => {
    // 尝试将日期字符串转换为时间戳进行比较
    const dateA = new Date(a.createTime).getTime()
    const dateB = new Date(b.createTime).getTime()
    
    // 如果日期解析有效，按日期降序排列
    if (!isNaN(dateA) && !isNaN(dateB)) {
      return dateB - dateA
    }
    
    // 后备方案：保留原来的版本号排序
    const versionA = a.version.split('.').map(Number)
    const versionB = b.version.split('.').map(Number)
    
    for (let i = 0; i < 3; i++) {
      if (versionA[i] !== versionB[i]) {
        return versionB[i] - versionA[i]
      }
    }
    return 0
  })
})

// 判断是否为当前使用版本
const isCurrentVersion = (version) => {
  return customNodeType.value && 
         customNodeType.value.currentVersionId === version.id
}

// 返回节点类型详情页
const goBack = () => {
  router.push(`/custom-nodes/${route.params.id}`)
}

// 返回节点类型列表页
const goToNodeTypesList = () => {
  router.push('/custom-nodes')
}

// 查看版本详情
const viewVersionDetail = (version) => {
  currentVersionDetail.value = version
  versionDetailVisible.value = true
}

// 确认发布版本
const confirmPublish = (version) => {
  if (isCurrentVersion(version)) return
  
  ElMessageBox.confirm(
    `确认将版本 v${version.version} 设为当前使用版本？`,
    '确认发布',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    publishVersion(version)
  }).catch(() => {
    // 用户取消操作
  })
}

// 发布版本
const publishVersion = async (version) => {
  publishing.value = true
  publishingVersionId.value = version.id
  try {
    await store.dispatch('publishCustomNodeVersion', {
      nodeTypeId: customNodeType.value.id,
      versionId: version.id
    })
    
    // 重新获取数据
    await fetchData()
    
    ElMessage.success(`版本 v${version.version} 已成功发布为当前使用版本`)
    
    // 如果在弹窗中，关闭弹窗
    if (versionDetailVisible.value) {
      versionDetailVisible.value = false
    }
  } catch (error) {
    ElMessage.error('发布版本失败: ' + error.message)
  } finally {
    publishing.value = false
    publishingVersionId.value = null
  }
}

// 跳转到基于选定版本创建新版本的详情页
const createFromVersion = (version) => {
  // 将版本数据存储到本地存储，以便详情页面可以获取
  localStorage.setItem('baseVersion', JSON.stringify(version))
  
  // 跳转到节点类型详情页
  router.push(`/custom-nodes/${route.params.id}`)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.version-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.code-section {
  margin-top: 20px;
}

.code-box {
  background-color: #f8f9fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
}

.code-box pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
}

.params-docs,
.return-docs {
  max-height: 100px;
}

.dialog-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}

.version-tag {
  font-family: 'Monaco', 'Menlo', monospace;
  font-weight: 600;
}

/* 按钮栏样式优化 */
.table-actions {
  display: flex;
  gap: 8px;
}

:deep(.el-table__empty-block) {
  min-height: 200px;
}

/* 分页组件样式 */
.pagination {
  margin-top: 20px;
  text-align: center;
}

.reference-count {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.info-icon {
  font-size: 14px;
  color: #909399;
}
</style> 